package cn.devcat.sso.controller;

import cn.devcat.sso.config.log.Log;
import cn.devcat.sso.entity.*;
import cn.devcat.sso.service.IBlogCommentService;
import cn.devcat.sso.service.IDevcatNoteService;
import cn.devcat.sso.service.INoteTextService;
import cn.devcat.sso.util.RsUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/note")
public class NoteController {

    @Autowired
    IDevcatNoteService noteService;

    @Autowired
    INoteTextService textService;

    @Autowired
    IBlogCommentService blogCommentService;

    @GetMapping
    public Rs getNoteList(SearchCommonParam param){
        PageData<DevcatNote> notePageData = noteService.getNotePageData(param);
        return RsUtil.success("加载成功",notePageData);
    }

    @GetMapping("/admin")
    public Rs getNoteListForAdmin(SearchCommonParam param){
      PageData<DevcatNote> notePageDataForAdmin = noteService.getNotePageDataForAdmin(param);
      return RsUtil.success("加载成功",notePageDataForAdmin);
    }

    @GetMapping("/byId")
    public Rs getNoteById(Long id){
      DevcatNote note = noteService.getNoteById(id);
      long count = blogCommentService.count(new QueryWrapper<BlogComment>().eq("note_id", id));
      note.setCommentCount((int)count);
      return RsUtil.success("查询成功", note);
    }

    @DeleteMapping
    public Rs delNote(@RequestBody List<Long> ids){
        noteService.delNote(ids, false);
        return RsUtil.success("删除成功");
    }

  @DeleteMapping("/admin")
  public Rs delNoteForAdmin(@RequestBody List<Long> ids){
    noteService.delNote(ids, true);
    return RsUtil.success("删除成功");
  }

    @PutMapping
    public Rs setNote(@RequestBody DevcatNote note){
        noteService.setNote(note);
        return RsUtil.success("修改成功");
    }

    @PutMapping("/viewType")
    public Rs changeViewType(@RequestBody DevcatNote note){
        noteService.changeViewType(note);
        return RsUtil.success("修改成功");
    }

    @GetMapping("/refresh")
    public Rs refresh(){
      textService.refreshCoverImage();
      return RsUtil.success("刷新成功");
    }

    @Log("增加笔记")
    @PostMapping
    public Rs addNote(@RequestBody DevcatNote note){
        noteService.addNote(note);
        return RsUtil.success("增加成功");
    }

    @PostMapping("/text")
    public Rs addNoteText(@RequestBody NoteText noteText){
        textService.addNoteText(noteText);
        return RsUtil.success("保存成功");
    }

    @GetMapping("/text")
    public Rs getNoteText(Long id){
        String noteText = textService.getNoteText(id);
        return RsUtil.success("加载成功",noteText);
    }
}
